package cn.vivi.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.vivi.domain.Product;
import cn.vivi.domain.User;
import cn.vivi.service.ProductService;
import cn.vivi.service.UserService;
import cn.vivi.service.impl.ProductServiceImpl;
import cn.vivi.service.impl.UserServiceImpl;
import cn.vivi.util.JsonUtils;
import cn.vivi.util.Result;

@WebServlet("/users")
public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;

	private UserService userService = new UserServiceImpl();

	private ProductService productService = new ProductServiceImpl();

	private void initParamer(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=utf8");
		initParamer(request, response);
		String method = this.request.getParameter("method");
		if ("findAll".equals(method)) {
			this.findUsers();
			return;
		}
		if ("login".equals(method)) {
			this.login();
		}
	}

	// 管理员登录
	private void login() {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		User loginUser = userService.login(user);
		if (Objects.isNull(loginUser)) {
			JsonUtils.toJson(response, Result.error());
		} else {
			JsonUtils.toJson(response, Result.success().createMap().setData("admin", loginUser));
		}
	}

	public void findUsers() throws IOException {
		List<User> users = userService.list();
		JsonUtils.toJson(response, Result.success().createMap().setData("items", users).setMessage("获得数据成功"));
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=utf8");
		StringBuffer data = new StringBuffer();
		String line = null;
		BufferedReader reader = null;
		reader = request.getReader();
		while (null != (line = reader.readLine())) {
			data.append(line);
		}
		Product product = (Product) JsonUtils.toObject(data.toString(), Product.class);
		if (productService.addProduct(product)) {
			JsonUtils.toJson(response, Result.success().setMessage("添加商品信息成功"));
		} else {
			JsonUtils.toJson(response, Result.error().setMessage("添加商品信息失败"));
		}
	}

}
